package com.alibaba.citrus.cr.mn.order.center.facade.service.impl;

import com.alibaba.citrus.cr.mn.order.center.facade.function.dataobject.AtomOrderDO;
import com.alibaba.citrus.cr.mn.order.center.facade.kafka.KafkaUtils;
import com.alibaba.citrus.cr.mn.order.center.facade.repository.AtomOrderQueryRepository;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.crb2btradecenter.domain.order.dto.QueryByOrderNosRequest;
import com.epoch.app.crb2btradecenter.domain.order.model.Order;
import com.epoch.app.crb2btradecenter.orderbackup.model.OrderBackUp;
import com.epoch.app.crb2btradecenter.orderbackup.service.OrderBackUpService;
import com.epoch.app.mnordercenter.contants.MnOrderCenterConstants;
import com.epoch.app.mnordercenter.notifymnsidesystem.dto.PostEventToMnRequest;
import com.epoch.app.mnordercenter.notifymnsidesystem.service.NotifyMnSideSystemService;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Primary
public class NotifyMnSideSystemServiceImpl implements NotifyMnSideSystemService {
    private static final Log log = Log.getLogger(NotifyMnSideSystemServiceImpl.class);

    @Resource
    private AtomOrderQueryRepository atomOrderQueryRepository;

    @Resource
    private OrderBackUpService orderBackUpService;

    @Override
    public Result<Void> postEventToMn(PostEventToMnRequest postEventToMnRequest) {
        log.info("NotifyMnSideSystemService#postEventToMn postEventToMnRequest: {}", postEventToMnRequest);
        if (StringUtils.isEmpty(postEventToMnRequest.getMessage())) {
            return Result.success(null);
        }
        try {
            log.info("销售订单发kafka消息的自消费消息:{}", postEventToMnRequest.getMessage());
            //commonAsyncMessageResponse
            JSONObject commonAsyncMessageResponseJsonObject = JSONObject.parseObject(postEventToMnRequest.getMessage());
            boolean automaticOrder = false;
            String businessUnitCode = null;
            String fromSys = null;
            String businessType = null;
            String eventCode = null;
            if (commonAsyncMessageResponseJsonObject.containsKey("businessUnitCode")) {
                businessUnitCode = (String) commonAsyncMessageResponseJsonObject.get("businessUnitCode");
            }
            if (commonAsyncMessageResponseJsonObject.containsKey("fromSys")) {
                fromSys = (String) commonAsyncMessageResponseJsonObject.get("fromSys");
            }
            if (commonAsyncMessageResponseJsonObject.containsKey("businessType")) {
                businessType = (String) commonAsyncMessageResponseJsonObject.get("businessType");
            }
            if (commonAsyncMessageResponseJsonObject.containsKey("eventCode")) {
                eventCode = (String) commonAsyncMessageResponseJsonObject.get("eventCode");
            }
            if (commonAsyncMessageResponseJsonObject.containsKey("data")) {
                List<Object> dataList = (List<Object>) commonAsyncMessageResponseJsonObject.get("data");
                for (Object obj : dataList) {
                    //pushOrderInfoToMnSideRequestOrderInfo
                    JSONObject pushOrderInfoToMnSideRequestOrderInfoJsonObject = JSONObject.parseObject(obj.toString());
                    if (pushOrderInfoToMnSideRequestOrderInfoJsonObject.containsKey("salesOrderNo")) {
                        String salesOrderNo = (String) pushOrderInfoToMnSideRequestOrderInfoJsonObject.get("salesOrderNo");
                        //查销售单获取预报单号
                        QueryByOrderNosRequest queryByOrderNosRequest = new QueryByOrderNosRequest();
                        queryByOrderNosRequest.setSalesOrderNo(Lists.newArrayList(salesOrderNo));
//                        queryByOrderNosRequest.setFromSys(fromSys);
//                        queryByOrderNosRequest.setBusinessUnitCode(businessUnitCode);
                        queryByOrderNosRequest.setPage(1);
                        queryByOrderNosRequest.setSize(10);
                        Result<List<AtomOrderDO>> listResult = atomOrderQueryRepository.queryByOrderNos(queryByOrderNosRequest);
                        if (listResult.isSuccess() && CollectionUtils.isNotEmpty(listResult.getResult())) {
                            Order order = listResult.getResult().get(0).getOrder();
                            if (StringUtils.isNotEmpty(order.getFeatures())) {
                                JSONObject jsonObject = JSONObject.parseObject(order.getFeatures());
                                if (jsonObject.containsKey("automaticOrder") && "true".equals(jsonObject.get("automaticOrder"))) {
                                    automaticOrder = true;
                                }
                            }
                        }
                        if (!automaticOrder) {
                            //需要查一次备表obtc_order_back_up，sap删除订单时，obtc_order表中记录会物理删除
                            if (StringUtils.isNotEmpty(eventCode)) {
                                if ("SalesOrder#delete".equals(eventCode)) {
                                    log.info("删除的订单从备表查:{}", postEventToMnRequest.getMessage());
                                    com.epoch.app.crb2btradecenter.orderbackup.dto.QueryByOrderBizIdsRequest queryByOrderBizIdsRequest = new com.epoch.app.crb2btradecenter.orderbackup.dto.QueryByOrderBizIdsRequest();
                                    queryByOrderBizIdsRequest.setOrderBizIds(Lists.newArrayList(salesOrderNo));
                                    queryByOrderBizIdsRequest.setPage(1);
                                    queryByOrderBizIdsRequest.setSize(10);
                                    queryByOrderBizIdsRequest.setLimit(10);
                                    Result<List<OrderBackUp>> ordersBackResult = orderBackUpService.queryByOrderBizIds(queryByOrderBizIdsRequest);
                                    if (ordersBackResult.isSuccess() && CollectionUtils.isNotEmpty(ordersBackResult.getResult())) {
                                        OrderBackUp orderBackUp = ordersBackResult.getResult().get(0);
                                        if (StringUtils.isNotEmpty(orderBackUp.getFeatures())) {
                                            JSONObject jsonObject = JSONObject.parseObject(orderBackUp.getFeatures());
                                            if (jsonObject.containsKey("automaticOrder") && "true".equals(jsonObject.get("automaticOrder"))) {
                                                automaticOrder = true;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            String messageKey = KafkaUtils.generateMessageKey(fromSys, businessType, businessUnitCode, eventCode);
            if (automaticOrder) {
                //用新topic发送
                log.info("send kafka message use auto fulfillment topic, key:{}, message:{}", messageKey, postEventToMnRequest.getMessage());
                KafkaUtils.send(MnOrderCenterConstants.AUTO_FULFILLMENT_ORDER_KAFKA_TOPIC(), messageKey, postEventToMnRequest.getMessage());
            } else {
                log.info("send kafka message use MN_KAFKA_TOPIC topic, key:{}, message:{}", messageKey, postEventToMnRequest.getMessage());
                KafkaUtils.send(MnOrderCenterConstants.MN_KAFKA_TOPIC(), messageKey, postEventToMnRequest.getMessage());
            }
        } catch (Exception e) {
            log.error("NotifyMnSideSystemService#postEventToMn pushSaleOrderInfo error", e);
        }
        return Result.success(null);
    }
}
